import React, { Component } from "react";

export default class Error extends Component {
  /**
   * @param hasError 是否存在错误
   */
  state = { hasError: "" };
  /**
   * 当该组件的子组件发生错误时调用
   * @param error 报错信息
   */
  static getDerivedStateFromError(error) {
    console.log("error :>> ", error);
    return { hasError: error };
  }
  render() {
    return (
      <div>
        <h3>Error Component</h3>
        {this.state.hasError !== "" ? "组件异常" : <Son></Son>}
      </div>
    );
  }
}

class Son extends Component {
  // 正常数据
  state = {
    arr: [
      { id: 1, name: "hyy", age: "18" },
      { id: 2, name: "yueyue", age: "18" },
    ],
  };
  errorData = () => {
    this.setState({ arr: "123" });
  };
  render() {
    return (
      <div>
        <h3>Son Componetns</h3>
        <button onClick={this.errorData}>error data</button>
        {this.state.arr.map((item) => {
          return (
            <h5 key={item.id}>
              name = {item.name} ---- age = {item.age}
            </h5>
          );
        })}
      </div>
    );
  }
}
